home *** CD-ROM | disk | FTP | other *** search
- Path: solon.com!not-for-mail
- From: wgb@netcom.com (Bill Bosacker)
- Newsgroups: comp.lang.c.moderated,comp.lang.c
- Subject: Re: Please help me elect rounding of int division
- Date: 22 Feb 1996 06:42:19 -0600
- Organization: WGB Enterprises
- Sender: clc@solutions.solon.com
- Approved: clc@solutions.solon.com
- Message-ID: <4ghobb$dpp@solutions.solon.com>
- References: <4gfaif$1tt@solutions.solon.com> <4ggbm9$85t@solutions.solon.com>
- NNTP-Posting-Host: solutions.solon.com
- X-Newsreader: Forte Agent .99d/32.182
-
- Gihan Perera <Gihan@andante.demon.co.uk> wrote:
-
- :In article <4gfaif$1tt@solutions.solon.com>
- : swedecj@vcnet.com "Carl Jacobson" writes:
- :
- :> Please help me solve this task.
- :>
- :> I have now tried (Borland C++ version 3.0) for two solid days to write
- :> a function that would allow me to round the quotient of (a/b) up or
- :> down based on the "nearest" integer instead of being truncated to the
- :> smallest. If exactly half way, return the "odd."
- :
- :The first part is easy. If you're using reals, add 0.5 to (a/b) before
- :truncating it. If you're doing the whole thing with integers, use:
- :
- : q = ( a + b/2 ) / b;
- :
- :which has the same effect.
- :
- :But neither of these meets your second criterion ("return the odd") -
- :they both round _up_ if exactly half-way. Sorry - I don't know any
- :easy trick for that.
-
- Try this:
-
- x = (a + b/2) / b;
- y = x - ((2 * (a % b) == b) && (!x & 1));
-
- The expression (2 * (a % b) == b) detects a remainder of exactly 0.5b
- and (!x & 1) returns 1 if x is even, thus assuring that y is odd.
-
- Later......
- ----------------------------------------------------------------------------
- WGB Enterprises Bill Bosacker
- P.O. Box 9267 wgb@netcom.com
- Whittier, CA 90608-9267 A TAG is a TAG is a TAG
-